package com.fitness.dao;

import com.fitness.entity.ProjectManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ManagerDAO extends BaseDAO {

    /**
     * 插入项目经理
     */
    public boolean insertManager(ProjectManager manager) {
        String sql = "INSERT INTO 项目经理表(经理姓名, 负责项目ID) VALUES (?, ?)";
        int affectedRows = executeUpdate(sql,
                manager.getManagerName(),
                manager.getResponsibleProjectId());
        return affectedRows > 0;
    }

    /**
     * 删除项目经理
     */
    public boolean deleteManager(int managerId) {
        String sql = "DELETE FROM 项目经理表 WHERE 经理ID = ?";
        int affectedRows = executeUpdate(sql, managerId);
        return affectedRows > 0;
    }

    /**
     * 关联查询：项目经理 + 项目名称
     */
    public List<ProjectManager> getManagerListWithProjectName() {
        List<ProjectManager> managerList = new ArrayList<>();
        String sql = "SELECT " +
                "    m.经理ID, " +
                "    m.经理姓名, " +
                "    m.负责项目ID, " +
                "    p.项目名称 " +
                "FROM 项目经理表 m " +
                "LEFT JOIN 项目表 p ON m.负责项目ID = p.项目ID";

        ResultSet rs = executeQuery(sql);
        try {
            while (rs != null && rs.next()) {
                ProjectManager manager = new ProjectManager();
                manager.setManagerId(rs.getInt("经理ID"));
                manager.setManagerName(rs.getString("经理姓名"));
                manager.setResponsibleProjectId(rs.getInt("负责项目ID"));
                manager.setProjectName(rs.getString("项目名称"));
                managerList.add(manager);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(null, null, rs);
        }
        return managerList;
    }

    /**
     * 检查项目是否已分配项目经理
     */
    public boolean isProjectAssigned(int projectId) {
        String sql = "SELECT COUNT(1) FROM 项目经理表 WHERE 负责项目ID = ?";
        ResultSet rs = executeQuery(sql, projectId);
        try {
            if (rs != null && rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(null, null, rs);
        }
        return false;
    }
}